﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BaseDal;
using Models;

namespace BaseBll
{
    public class PurchasePayRegistBll
    {
        private static readonly Lazy<PurchasePayRegistBll> _instance = new Lazy<PurchasePayRegistBll>(() => new PurchasePayRegistBll());

        public static PurchasePayRegistBll Instance { get; } = _instance.Value;

        private PurchasePayRegistBll()
        { }

        // 获取单例实例
        private readonly PurchasePayRegistDal DalInstance = PurchasePayRegistDal.Instance;

        /// <summary>
        /// 查询数据是否存在
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public bool IsExist(string strWhere)
        {
            return DalInstance.IsExist(strWhere);
        }

        /// <summary>
        /// 查询分页数据
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="strWhere"></param>
        /// <param name="filedOrder"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetPageList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            return DalInstance.GetPageList(pageSize, pageIndex, strWhere, filedOrder, out recordCount);
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="strWhere"></param>
        /// <returns></returns>
        public List<PurchasePayRegistHead> GetList(string strWhere)
        {
            return DalInstance.GetList(strWhere);
        }

        /// <summary>
        /// 根据id查询实体类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PurchasePayRegistHead GetModelById(decimal id)
        {
            return DalInstance.GetModelById(id);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public bool AddPurchasePayRegist(PurchasePayRegistHead model, List<PurchaseRequestBody> prbList)
        {
            return DalInstance.AddPurchasePayRegist(model, prbList);
        }

        /// <summary>
        /// 删除一条数据，及子表所有相关数据
        /// </summary>
        public bool DeletePurchasePayRegist(decimal ID)
        {
            return DalInstance.DeletePurchasePayRegist(ID);
        }

        /// <summary>
        /// 验证model各字段合法性
        /// </summary>
        /// <param name="model"></param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public bool VerifyModel(PurchasePayRegistHead model, ref string msg)
        {
            string strWhere;
            if (model.ID > 0)
            {
                strWhere = " and PPR_Number='" + model.PPR_Number + "' and ID !=" + model.ID;
            }
            else
            {
                strWhere = " and PPR_Number='" + model.PPR_Number + "'";
            }
            if (IsExist(strWhere))
            {
                msg = "付款编号已存在";
                return false;
            }

            // 获取公司名称
            Department company = DeptBll.Instance.GetModelById(model.PPR_CompanyId);
            if (company != null)
            {
                model.PPR_CompanyName = company.FullName;
            }
            else
            {
                msg = "所选公司不存在";
                return false;
            }

            // 获取部门名称
            Department dept = DeptBll.Instance.GetModelById(model.PPR_DeptId);
            if (dept != null)
            {
                model.PPR_DeptName = dept.FullName;
            }
            else
            {
                msg = "所选部门不存在";
                return false;
            }

            // 获取供应商名称
            Supplier supplier = SupplierBll.Instance.GetModelById(model.PPR_SupplierId);
            if (supplier != null)
            {
                model.PPR_SupplierName = supplier.S_Name;
                model.PPR_Bank = supplier.S_Bank;
                model.PPR_BankNumber = supplier.S_BankNumber;
            }
            else
            {
                msg = "所选供应商不存在";
                return false;
            }

            return true;
        }

        /// <summary>
        /// 通过付款登记子表集合获取采购申请子表集合
        /// </summary>
        /// <param name="pprblist"></param>
        /// <returns></returns>
        public List<PurchaseRequestBody> GetPRBList(List<PurchasePayRegistBody> pprblist)
        {
            var resultList = new List<PurchaseRequestBody>();

            if (pprblist == null || pprblist.Count == 0)
                return resultList;

            // 按 PPR_ApplyNo 分组，减少对 GetModelByNo 的调用次数
            var groupedPprbList = pprblist
                .Where(p => !string.IsNullOrEmpty(p.PPR_ApplyNo))
                .GroupBy(p => p.PPR_ApplyNo);

            foreach (var group in groupedPprbList)
            {
                // 获取采购申请主表
                var prhModel = PurchaseRequestBll.Instance.GetModelByNo(group.Key);

                if (prhModel == null)
                    continue;

                // 采购申请子表
                var prbList = prhModel.ItemList;

                if (prbList == null || prbList.Count == 0)
                    continue;

                // 匹配并更新支付金额
                var updatedPrbList = prbList
                    .Join(group,
                          prb => prb.PR_ItemID,
                          pprb => pprb.PPR_ItemID,
                          (prb, pprb) => new { prb, pprb })
                    .Select(joined =>
                    {
                        joined.prb.PR_Paid += joined.pprb.PPR_RegistPay;
                        return joined.prb;
                    })
                    .ToList();

                resultList.AddRange(updatedPrbList);
            }

            return resultList;
        }

    }
}
